package com.ruoyi.business.listener;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.cm.domain.CmBsProcessInspection;
import com.ruoyi.cm.domain.bo.CmBaContractSheetsBo;
import com.ruoyi.cm.domain.bo.CmBsContractInfoBo;
import com.ruoyi.cm.domain.bo.CmBsStartAdvanceBo;
import com.ruoyi.cm.domain.bo.CmReportBo;
import com.ruoyi.cm.domain.vo.*;
import com.ruoyi.cm.mapper.CmBsProcessInspectionMapper;
import com.ruoyi.cm.service.ICmBaContractSheetsService;
import com.ruoyi.cm.service.ICmBsContractInfoService;
import com.ruoyi.cm.service.ICmBsStartAdvanceService;
import com.ruoyi.cm.service.ICmReportService;
import com.ruoyi.common.wecom.constants.WeComUrlConstants;
import com.ruoyi.ma.domain.MaMaterialPlan;
import com.ruoyi.ma.domain.MaReportFormPayment;
import com.ruoyi.ma.domain.vo.MaMaterialPlanVo;
import com.ruoyi.ma.mapper.MaMaterialPlanMapper;
import com.ruoyi.ma.mapper.MaReportFormPaymentMapper;
import com.ruoyi.workflow.event.CopyUserEvent;
import com.ruoyi.workflow.event.NeedRollBackEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.api.delegate.event.FlowableEventType;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import static com.ruoyi.business.constant.BusinessConstants.*;

/**
 * 取消申请、任务拒绝（驳回）时 ----  业务的回退
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RollBackBusinessListener implements FlowableEventListener {

    private final ICmBsStartAdvanceService cmBsStartAdvanceService;

    private final ICmBaContractSheetsService iCmBaContractSheetsService;

    private final ICmBsContractInfoService iCmBsContractInfoService;
    private final CmBsProcessInspectionMapper processInspectionMapper;
    private final MaMaterialPlanMapper planMapper;
    private final MaReportFormPaymentMapper paymentMapper;

    //报表管理
    private final ICmReportService reportService;
    @Override
    public Collection<? extends FlowableEventType> getTypes() {
        return null;
    }

    @Override
    public void onEvent(FlowableEvent flowableEvent) {

    }

    /**
     * 取消申请、任务拒绝（驳回）时 ----  业务的回退
     */
    @EventListener
    public void onNeedRollBackEvent(NeedRollBackEvent event) {
        log.debug("NeedRollBackEvent监听器，监听成功");
        Map<String, Object> processVariables = event.getProcessVariables();
        String processDefinitionKey = event.getProcessDefinitionKey();
        // TODO 取消申请、任务拒绝（驳回）时 ----  业务的回退
        if (processDefinitionKey.startsWith(GCKZFSHBBSPLC_PROCESS_KEY)) {
            // Eg: 1. 工程款支付审核报表审批流程
            Long bdId = (Long)processVariables.get("bdId");
            Long qsId = (Long)processVariables.get("qsId");
            CmReportBo bo =new CmReportBo();
            bo.setBdId(bdId);
            bo.setQsId(qsId);
            List<CmReportVo> cmReportVos = reportService.queryList(bo);
            if(CollUtil.isNotEmpty(cmReportVos)){
                CmReportVo cmReportVo = cmReportVos.get(0);
                if("11".equals(cmReportVo.getStatus())){
                    bo.setStatus("33");
                    reportService.updateStatusByBo(bo);
                }
            }

            log.debug(" 在工程款支付审核报表审批流程    取消申请、任务拒绝（驳回）时 ----  业务的回退 TODO 相关业务操作");
        }
        if (processDefinitionKey.startsWith(GXBYSPLC_PROCESS_KEY)) {
            // Eg: 1. 工序报验审批流程
            Long id = (Long) processVariables.get("id");
            CmBsProcessInspection inspection = processInspectionMapper.selectById(id);
            if (inspection != null && "11".equals(inspection.getApproveStatus())) {
                String taskComment = processVariables.get("taskComment").toString();
                inspection.setApprovalOpinions(StringUtils.isBlank(taskComment) ? "" : taskComment);
                inspection.setApproveStatus("33");
                processInspectionMapper.updateById(inspection);
            }
            log.debug(" 在工序报验审批流程    取消申请、任务拒绝（驳回）时 ----  业务的回退 TODO 相关业务操作");
        }
        if (processDefinitionKey.startsWith(HTSPLC_PROCESS_KEY)) {
            // Eg: 1. 合同审批流程
            Long bdId = (Long) processVariables.get("bdId");
            Long contractId = (Long) processVariables.get("contractId");
            CmBsContractInfoBo cmBsContractInfoBo = new CmBsContractInfoBo();
            cmBsContractInfoBo.setBdId(bdId);
            List<CmBsContractInfoVo> cmBsContractInfoVos = iCmBsContractInfoService.queryList(cmBsContractInfoBo);
            if (CollectionUtils.isNotEmpty(cmBsContractInfoVos)){
                if ("11".equals(cmBsContractInfoVos.get(0).getApprovalStatus())){
                    cmBsContractInfoBo.setContractId(contractId);
                    cmBsContractInfoBo.setApprovalStatus("33");
                    iCmBsContractInfoService.updateApprovalStatusByBo(cmBsContractInfoBo);
                    log.debug(" 在合同审批流程    取消申请、任务拒绝（驳回）时 ----  业务的回退 TODO 相关业务操作");
                }
            }
        }
        if (processDefinitionKey.startsWith(HTBGSPLC_PROCESS_KEY)) {
            // Eg: 1. 合同变更审批流程
            Long bdId = (Long) processVariables.get("bdId");
            Long contractId = (Long) processVariables.get("contractId");
            CmBsContractInfoBo cmBsContractInfoBo = new CmBsContractInfoBo();
            cmBsContractInfoBo.setBdId(bdId);
            List<CmBsContractInfoVo> cmBsContractInfoVos = iCmBsContractInfoService.queryList(cmBsContractInfoBo);
            if (CollectionUtils.isNotEmpty(cmBsContractInfoVos)){
                if ("11".equals(cmBsContractInfoVos.get(0).getChgApprovalStatus())){
                    cmBsContractInfoBo.setContractId(contractId);
                    cmBsContractInfoBo.setChgApprovalStatus("33");
                    iCmBsContractInfoService.updateChgApprovalStatusByBo(cmBsContractInfoBo);
                    log.debug(" 在合同变更审批流程    取消申请、任务拒绝（驳回）时 ----  业务的回退 TODO 相关业务操作");
                }
            }
        }
        if (processDefinitionKey.startsWith(HTZDQDSPLC_PROCESS_KEY)) {
            // Eg: 1. 合同站点清单审批流程
            Long bdId = (Long) processVariables.get("bdId");
            Long zdId = (Long) processVariables.get("zdId");
            CmBaContractSheetsBo cmBaContractSheetsBo = new CmBaContractSheetsBo();
            cmBaContractSheetsBo.setBdId(bdId);
            cmBaContractSheetsBo.setZdId(zdId);
            List<CmBaContractSheetsVo> cmBaContractSheetsVos = iCmBaContractSheetsService.selectList(cmBaContractSheetsBo);
            if (CollectionUtils.isNotEmpty(cmBaContractSheetsVos)){
                if ("11".equals(cmBaContractSheetsVos.get(0).getApprovalStatus())){
                    cmBaContractSheetsBo.setApprovalStatus("33");
                    iCmBaContractSheetsService.updateApprovalStatusByBo(cmBaContractSheetsBo);
                    log.debug(" 在合同站点清单审批流程    取消申请、任务拒绝（驳回）时 ----  业务的回退 TODO 相关业务操作");
                }
            }
        }
        if (processDefinitionKey.startsWith(KGYFK_PROCESS_KEY)) {
            // Eg: 1. 开工预付款审批流程
            Long bdId = (Long) processVariables.get("bdId");
            CmBsStartAdvanceBo cmBsStartAdvanceBo = new CmBsStartAdvanceBo();
            cmBsStartAdvanceBo.setBdId(bdId);
            List<CmBsStartAdvanceVo> cmBsStartAdvanceVos = cmBsStartAdvanceService.queryList(cmBsStartAdvanceBo);
            if (CollectionUtils.isNotEmpty(cmBsStartAdvanceVos)){
                if ("11".equals(cmBsStartAdvanceVos.get(0).getReportFlag())){
                    cmBsStartAdvanceBo.setReportFlag("33");
                    cmBsStartAdvanceService.updateApprovalStatusByBo(cmBsStartAdvanceBo);
                    log.debug(" 在开工预付款审批流程    取消申请、任务拒绝（驳回）时 ----  业务的回退 TODO 相关业务操作");
                }
            }

        }
        if (processDefinitionKey.startsWith(JGC_PROCESS_KEY)) {
            // Eg: 1. 甲供材审批流程
            Long planId = (Long) processVariables.get("planId");
            MaMaterialPlan plan = planMapper.selectById(planId);
            if (plan != null && "11".equals(plan.getWorkflowsStateus())) {
                plan.setWorkflowsStateus("33");
                planMapper.updateById(plan);
                log.debug(" 在甲供材审批流程    取消申请、任务拒绝（驳回）时 ----  业务的回退 TODO 相关业务操作");
            }
        }
        if (processDefinitionKey.startsWith(JGCBB_PROCESS_KEY)) {
            // Eg: 1. 甲供材报表审批流程
            Long reportId = (Long) processVariables.get("reportId");
            MaReportFormPayment payment = paymentMapper.selectById(reportId);
            if (payment != null && "11".equals(payment.getWorkflowsStateus())) {
                payment.setWorkflowsStateus("33");
                paymentMapper.updateById(payment);
                log.debug(" 在甲供材报表审批流程    取消申请、任务拒绝（驳回）时 ----  业务的回退 TODO 相关业务操作");
            }
        }
        if (processDefinitionKey.startsWith(HTZDQDBGSPLC_PROCESS_KEY)) {
            // Eg: 1. 合同站点清单变更审批流程
            Long bdId = (Long) processVariables.get("bdId");
            Long zdId = (Long) processVariables.get("zdId");
            CmBaContractSheetsBo cmBaContractSheetsBo = new CmBaContractSheetsBo();
            cmBaContractSheetsBo.setBdId(bdId);
            cmBaContractSheetsBo.setZdId(zdId);
            List<CmBaContractSheetsVo> cmBaContractSheetsVos = iCmBaContractSheetsService.selectList(cmBaContractSheetsBo);
            if (CollectionUtils.isNotEmpty(cmBaContractSheetsVos)){
                if ("11".equals(cmBaContractSheetsVos.get(0).getChgApprovalStatus())){
                    cmBaContractSheetsBo.setChgApprovalStatus("33");
                    iCmBaContractSheetsService.updateApprovalStatusByBo(cmBaContractSheetsBo);
                    log.debug(" 在合同站点清单变更审批流程    取消申请、任务拒绝（驳回）时 ----  业务的回退 TODO 相关业务操作");
                }
            }
        }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }


}
